//
//  ZXEmptyViewController.m
//  YiShangbao
//
//  Created by simon on 17/3/9.
//  Copyright © 2017年 com.Microants. All rights reserved.
//

#import "ZXEmptyViewController.h"
#import "AFNetworkReachabilityManager.h"
#import "Masonry.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "CAIErrorSolutionWebController.h"
#import "EmptyViewKitTool.h"

// 注意： beginAppearanceTransition: /endAppearanceTransition 方法没必要写，自定义显示回调机制的时候才使用，系统默认也会回调viewWillAppear等方法的

///页面类型
typedef NS_ENUM(NSInteger, ZXEmptyViewPageType)
{
    ///空数据页面
    ZXEmptyViewPageTypeNoData = 0,
    ///加载失败页面
    ZXEmptyViewPageTypeRequestFailed = 1,
};

///页面请求失败的按钮展示类型包含哪几种类型
typedef NS_ENUM(NSInteger, ZXEmptyViewErrorButtonType)
{
    ///重新请求
    ZXEmptyViewErrorButtonTypeReload = 0,
    ///重新请求和解决方案
    ZXEmptyViewErrorButtonTypeReloadAndSolution = 1,
};

@interface ZXEmptyViewController ()

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *textLabel;
@property (nonatomic, strong) UIButton *centerButton;
///是否展示中间按钮
@property (nonatomic, assign) BOOL showCenterButton;
///中间按钮事件类型
@property (nonatomic, assign) ZXEmptyViewActionType buttonActionType;
///touchEvent类型
@property (nonatomic, assign) ZXEmptyViewTouchEventType touchEventType;
///页面类型
@property (nonatomic, assign) ZXEmptyViewPageType emptyViewPageType;
///页面请求失败的按钮展示类型包含哪几种类型
@property (nonatomic, assign) ZXEmptyViewErrorButtonType emptyViewErrorButtonType;




@property (nonatomic, assign, readonly) CGFloat safeAreaStatusBarHeight;


/// 按钮 与 (标题或图片) 之间的间距, default is 30.
@property (nonatomic, assign) CGFloat actionBtnMarginTop;


////-------------------------- Button 相关 --------------------------//
/// 按钮文字
@property (nonatomic, copy) NSString *actionBtnTitle;

/// 按钮文字颜色
@property (nonatomic, strong) UIColor *actionBtnTitleColor;

/// 按钮字体, 大小default is 14.f
@property (nonatomic, strong) UIFont *actionBtnFont;

/// 按钮的{width,height},default is {120.f, 30.f}
@property (nonatomic, assign) CGSize  actionBtnSize;

/// 按钮宽带是否自动适配,默认YES；
@property (nonatomic, assign) BOOL  actionBtnWidthAutomic;

/// 按钮的圆角大小, default is 0
@property (nonatomic, assign) CGFloat  actionBtnCornerRadius;

/// 按钮边框border的宽度, default is 0
@property (nonatomic, assign) CGFloat  actionBtnBorderWidth;

/// 按钮边框颜色
@property (nonatomic, strong) UIColor *actionBtnBorderColor;

/// 按钮背景颜色
@property (nonatomic, strong) UIColor *actionBtnBackgroundColor;

@end

@implementation ZXEmptyViewController
@synthesize customButtonConfig = _customButtonConfig;

#pragma mark - 生命周期

#pragma mark -(1)
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}
- (void)initData
{
    self.showErrorCodeOnLabelText = NO;
    self.showErrorCodeOnToastText = YES;
    self.showEmptyErrorViewWithErrorToast = YES;
    self.emptyErrorViewTouchEvent =  [CAIEmptyViewGlobalConfig sharedInstance].emptyErrorViewTouchEvent;
    self.showEmptyErrorViewReloadButton =  [CAIEmptyViewGlobalConfig sharedInstance].showEmptyErrorViewReloadButton;
    
    self.actionBtnFont = [UIFont systemFontOfSize:LCDScale_iPhone6(14)];
    self.actionBtnSize = CGSizeMake(LCDScale_iPhone6(120), LCDScale_iPhone6(30));
    self.actionBtnWidthAutomic = YES;
    self.actionBtnMarginTop = LCDScale_iPhone6(30);
}

#pragma mark -(3)
///addChildViewController和addSubview后才会回调这里开始加载对象;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


/// 调整imageView，button按钮的位置和大小；(4)
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    CGFloat btnHeight = self.actionBtnSize.height;
    CGFloat btnWidth = self.actionBtnSize.width;
    CGFloat titleLabTopToImageConstant = 12;
    CGFloat buttonTopToTitleLabConstant = self.actionBtnMarginTop;
    CGFloat buttonTopToImageConstant = self.actionBtnMarginTop;
    
    // imageView调整
    [self.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.imageView.image.size);
    }];
    /// 确立imageView的中心点
    /// 有提示语
    if (self.textLabel.text.length>0 )
    {
        CGRect titleLabRect = [self.textLabel.text boundingRectWithSize:CGSizeMake(LCDW-LCDScale_iPhone6(24), MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.textLabel.font} context:nil];

        CGFloat otherContentHeight = 0.f;
        //有点击加载按钮；
        if (!self.centerButton.hidden)
        {
            otherContentHeight = titleLabTopToImageConstant+titleLabRect.size.height + buttonTopToTitleLabConstant + btnHeight;
        }
        //无点击加载按钮
        else
        {
            otherContentHeight = titleLabTopToImageConstant+titleLabRect.size.height;
        }
        
        [self.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
            
            make.centerY.mas_equalTo (self.view.mas_centerY).offset(-otherContentHeight/2-64+self.contentOffest.height);
        }];
    }
    //无提示语，有加载按钮；
    else if (self.textLabel.text.length == 0 && !self.centerButton.hidden)
    {
        CGFloat otherContentHeight = titleLabTopToImageConstant + buttonTopToTitleLabConstant + btnHeight;
        [self.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo (self.view.mas_centerY).offset(-otherContentHeight/2-64+self.contentOffest.height);
        }];
    }
    //无提示语，无加载按钮；
    else if (self.textLabel.text.length==0 && self.centerButton.hidden)
    {
        [self.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo (self.view.mas_centerY).offset(-64+self.contentOffest.height);
        }];
    }

    
    // centerButton调整
    
    if (!self.centerButton.hidden)
    {
        //宽度
        CGRect titleLabRect = [self.centerButton.currentTitle boundingRectWithSize:CGSizeMake(LCDW-LCDScale_iPhone6(24), MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.centerButton.titleLabel.font} context:nil];
        //偏移
        CGFloat centerButtonToTitleLabelOffest = buttonTopToTitleLabConstant;
        if (self.textLabel.text.length==0) {
            centerButtonToTitleLabelOffest = buttonTopToImageConstant - titleLabTopToImageConstant;
        }
        [self.centerButton mas_updateConstraints:^(MASConstraintMaker *make) {
            if (self.actionBtnWidthAutomic) {
                make.width.mas_equalTo(titleLabRect.size.width + btnHeight);
            }else{
                make.width.mas_equalTo(btnWidth);
            }
            make.height.mas_equalTo(btnHeight);
            make.top.mas_equalTo(self.textLabel.mas_bottom).offset(centerButtonToTitleLabelOffest);
        }];
    }
}

#pragma mark - setUI

- (void)setUI
{
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.textLabel];
    [self.view addSubview:self.centerButton];
    
    self.showEmptyViewCenterButton = NO;
    
    CGSize size = self.actionBtnSize;
    // fix 2022.6.30 :解决默认设置imageView尺寸问题；
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.centerY.mas_equalTo (self.view.mas_centerY).offset(-64+self.contentOffest.height);
    }];
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.imageView.mas_bottom).offset(12);
        make.left.mas_equalTo(self.view.mas_left).offset(LCDScale_iPhone6(12));
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    [self.centerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textLabel.mas_bottom).offset(self.actionBtnMarginTop);
        make.size.mas_equalTo(size);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    
    [self setUpTextLabel];

}


- (void)setUpTextLabel{
    if (self.textAppearance.font) {
        self.textLabel.font = self.textAppearance.font;
    }
    if (self.textAppearance.textColor) {
        self.textLabel.textColor = self.textAppearance.textColor;
    }
}


#pragma mark - 懒加载

- (UIImageView *)imageView
{
    if (!_imageView) {
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.contentMode = UIViewContentModeScaleToFill;
        _imageView = imgView;
    }
    return _imageView;
}

- (UILabel *)textLabel
{
    if (!_textLabel) {
        UILabel *lab = [[UILabel alloc] init];
        lab.numberOfLines = 0;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.textColor = UIColorFromRGB_HexValue(0x666666);
        lab.font = [UIFont systemFontOfSize:LCDScale_iPhone6(14)];
        _textLabel = lab;
    }
    return _textLabel;
}

- (UIButton *)centerButton
{
    if (!_centerButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"点击加载" forState:UIControlStateNormal];
        [self setView:btn cornerRadius:5.f borderWidth:1.f borderColor:[UIColor colorWithWhite:0.8 alpha:1]];
        [btn setTitleColor:[UIColor colorWithWhite:0.3 alpha:1] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:LCDScale_iPhone6(14)];
        [btn addTarget:self action:@selector(updateNewData:) forControlEvents:UIControlEventTouchUpInside];
        _centerButton = btn;
    }
    return _centerButton;
}

- (void)setView:(UIView *)view cornerRadius:(CGFloat)radius borderWidth:(CGFloat)width borderColor:(UIColor *)color
{
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = radius;
    view.layer.borderWidth = width;
    view.layer.borderColor =color?[color CGColor]:[UIColor clearColor].CGColor;
}

- (EmptyCustomCenterButtonConfig *)customButtonConfig
{
    if (!_customButtonConfig) {
        _customButtonConfig = [[EmptyCustomCenterButtonConfig alloc] init];
    }
    return _customButtonConfig;
}



#pragma mark - 实例方法

// 网络问题-“查看解决方案”按钮，服务器问题--"点击加载"按钮-
- (void)addEmptyViewInController:(UIViewController *)viewController
                    hasLocalData:(BOOL)flag
                           error:(nullable NSError *)error
                      emptyImage:(nullable UIImage *)image
                      emptyTitle:(nullable NSString *)title API_DEPRECATED("分成2个方法-addEmptyViewInController:和addEmptyErrorViewInController: instead.", ios(2.0, 15.0))
{
    if (error) {
        [self addEmptyErrorViewInController:viewController hasLocalData:flag error:error emptyImage:image emptyTitle:title];
    }else{
        [self addEmptyViewInController:viewController hasLocalData:flag emptyImage:image emptyTitle:title];
    }
}


- (void)addEmptyViewInController:(UIViewController *)viewController
                    hasLocalData:(BOOL)flag
                      emptyImage:(nullable UIImage *)image
                      emptyTitle:(nullable NSString *)title
{
    [self addEmptyViewInController:viewController hasLocalData:flag emptyImage:image emptyTitle:title buttonHide:YES];
}

- (void)addEmptyViewInController:(UIViewController *)viewController
                    hasLocalData:(BOOL)flag
                      emptyImage:(nullable UIImage *)image
                      emptyTitle:(nullable NSString *)title
                      buttonHide:(BOOL)hide{
    self.showEmptyViewCenterButton = !hide;
    [self setEmptyViewInControllerConfig];
    [self setEmptyAndErrorViewInController:viewController hasLocalData:flag error:nil image:image title:title];
    [self reloadEmptyViewInControllerUI];
}

#pragma mark - ErrorView

#pragma mark -(2)
- (void)addEmptyErrorViewOnlyUpdateBtnInController:(UIViewController *)viewController
                                      hasLocalData:(BOOL)flag
                                             error:(nullable NSError *)error{
    [self addEmptyErrorViewOnlyUpdateBtnInController:viewController hasLocalData:flag error:error emptyImage:nil emptyTitle:nil];
}

- (void)addEmptyErrorViewOnlyUpdateBtnInController:(UIViewController *)viewController
                                      hasLocalData:(BOOL)flag
                                             error:(nullable NSError *)error
                                        emptyImage:(nullable UIImage *)image
                                        emptyTitle:(nullable NSString *)title{
    
    self.emptyViewErrorButtonType = ZXEmptyViewErrorButtonTypeReload;
    [self setErrorViewWithUpdateButtonInControllerConfig];
    // 会调用viewDidLoad
    [self setEmptyAndErrorViewInController:viewController hasLocalData:flag error:error image:image title:title];
    [self reloadErrorViewWithUpdateButtonInControllerUI];
}

- (void)addEmptyErrorViewInController:(UIViewController *)viewController
                    hasLocalData:(BOOL)flag
                           error:(nullable NSError *)error
                      emptyImage:(nullable UIImage *)image
                      emptyTitle:(nullable NSString *)title{
    [self setEmptyErrorViewInController:viewController hasLocalData:flag error:error emptyImage:image emptyTitle:title];
}

- (void)addEmptyErrorViewInController:(UIViewController *)viewController
                    hasLocalData:(BOOL)flag
                           error:(nullable NSError *)error{
    [self setEmptyErrorViewInController:viewController hasLocalData:flag error:error emptyImage:nil emptyTitle:nil];
}


- (void)setEmptyErrorViewInController:(UIViewController *)viewController
                    hasLocalData:(BOOL)flag
                           error:(nullable NSError *)error
                      emptyImage:(nullable UIImage *)image
                      emptyTitle:(nullable NSString *)title
{
    if (error)
    {
        if (error.code == -1005 || error.code == -1009 || error.code == -1001)
        {
            [self setErrorViewWithSolutionButtonInControllerConfig];
            [self setEmptyAndErrorViewInController:viewController hasLocalData:flag error:error image:image title:title];
            [self reloadErrorViewWithSolutionButtonInControlleUI];
            return;
        }
    }
    [self setErrorViewWithUpdateButtonInControllerConfig];
    // 会调用viewDidLoad
    [self setEmptyAndErrorViewInController:viewController hasLocalData:flag error:error image:image title:title];
    [self reloadErrorViewWithUpdateButtonInControllerUI];
}

#pragma mark 最终方法
///error == nil或等于self.emptyViewType == ZXEmptyViewTypeNoData,则表示请求成功的空氛围图，也不会有点击屏幕事件；
- (void)setEmptyAndErrorViewInController:(UIViewController *)viewController
                         hasLocalData:(BOOL)flag
                                error:(nullable NSError *)error
                                image:(nullable UIImage *)image
                                title:(nullable NSString *)title
{    
    //->请求错误或成功
    if (flag)
    {
        if (self.emptyViewPageType == ZXEmptyViewPageTypeRequestFailed)
        {
            //加在已显示页面上；
            [self zx_makeToastInViewController:viewController withError:error];
        }
        //success
        else
        {
            [self removeEmptyViewInContainerViewConroller];
        }
    }
    //->请求错误或成功或空数据;本地还没有数据;
    else
    {
        if (self.emptyViewPageType == ZXEmptyViewPageTypeRequestFailed) {
            if (!image) {
                image = [CAIEmptyViewGlobalConfig sharedInstance].failedImage;
            }
            if (!title) {
                title = [CAIEmptyViewGlobalConfig sharedInstance].failedTitle;
            }
        }
        [self zx_addChildViewControllerInController:viewController];
        self.imageView.image = image;
        self.textLabel.text = [self zx_finallyTextLabelTitle:title withError:error];
        //加在当前失败viewController上
        if (error && self.showEmptyErrorViewWithErrorToast)
        {
            [self zx_makeToastInViewController:self withError:error];
        }
    }
}


#pragma mark - 设置数据配置

// 空数据氛围视图,按钮有可能出现或不出现；
- (void)setEmptyViewInControllerConfig{
    self.emptyViewPageType = ZXEmptyViewPageTypeNoData;
    self.touchEventType = ZXEmptyViewTouchEventTypeNone;
    self.buttonActionType = ZXEmptyViewActionTypeCustomButton;
}
- (void)reloadEmptyViewInControllerUI
{
    if (self.showCenterButton) {
        [self setUpActionButtonConfiguration];
    }
}

// error-解决方案按钮。
- (void)setErrorViewWithSolutionButtonInControllerConfig
{
    self.emptyViewPageType = ZXEmptyViewPageTypeRequestFailed;
    self.touchEventType = ZXEmptyViewTouchEventTypeReload;
    self.buttonActionType = ZXEmptyViewActionTypeErrorSolution;
}
- (void)reloadErrorViewWithSolutionButtonInControlleUI
{
    self.showCenterButton = YES;
    [self setUpActionButtonConfiguration];
}

// error-重新请求按钮是否展示；点击空白区域是否事件回调；如果点击空白区域回调，则隐藏按钮；
- (void)setErrorViewWithUpdateButtonInControllerConfig
{
    self.emptyViewPageType = ZXEmptyViewPageTypeRequestFailed;
    self.touchEventType = self.emptyErrorViewTouchEvent ? ZXEmptyViewTouchEventTypeReload:
    ZXEmptyViewTouchEventTypeNone;
    self.buttonActionType = ZXEmptyViewActionTypeReload;
}
- (void)reloadErrorViewWithUpdateButtonInControllerUI
{
    self.showCenterButton = self.showEmptyErrorViewReloadButton;
    if (self.showCenterButton) {
        [self setUpActionButtonConfiguration];
    }
}


- (void)setUpActionButtonConfiguration
{
    ///原则上需要对不同按钮做不同配置处理
    if (self.buttonActionType == ZXEmptyViewActionTypeReload) {
        self.actionBtnTitle = @"点击加载";
        self.actionBtnTitleColor = UIColorFromRGB_HexValue(0x666666);
        self.actionBtnSize = CGSizeMake(LCDScale_iPhone6(120), LCDScale_iPhone6(30));
        self.actionBtnWidthAutomic = YES;
        self.actionBtnCornerRadius = 15;
        self.actionBtnBorderColor = UIColorFromRGB_HexValue(0xCCCCCC);
        self.actionBtnFont = [UIFont systemFontOfSize:14];
        self.actionBtnMarginTop = 30;
    }
    else if (self.buttonActionType == ZXEmptyViewActionTypeErrorSolution)
    {
        self.actionBtnTitle = @"查看解决方案";
        self.actionBtnTitleColor = [UIColor colorWithWhite:0.3 alpha:1];
        self.actionBtnSize = CGSizeMake(LCDScale_iPhone6(120), LCDScale_iPhone6(30));
        self.actionBtnWidthAutomic = YES;
        self.actionBtnBorderColor = [UIColor colorWithWhite:0.8 alpha:1];
        self.actionBtnCornerRadius = 5;
        self.actionBtnFont = [UIFont systemFontOfSize:14];
        self.actionBtnMarginTop = 30;
    }else{
        [self setUpCustomActionButtonConfiguration];
    }
}

- (void)setUpCustomActionButtonConfiguration{
    
    EmptyCustomCenterButtonConfig *config = self.customButtonConfig;
    self.actionBtnTitleColor = config.appearance.actionBtnTitleColor;
    self.actionBtnFont = config.appearance.actionBtnFont;
    self.actionBtnBackgroundColor = config.appearance.actionBtnBackgroundColor;
    self.actionBtnBorderColor = config.appearance.actionBtnBorderColor;
    self.actionBtnBorderWidth = config.appearance.actionBtnBorderWidth;
    self.actionBtnCornerRadius = config.appearance.actionBtnCornerRadius;
    self.actionBtnWidthAutomic = config.appearance.actionBtnWidthAutomic;
    self.actionBtnSize = config.appearance.actionBtnSize;
    self.actionBtnMarginTop = config.appearance.actionBtnMarginTop;

    self.actionBtnTitle = config.actionBtnTitle;
}

#pragma mark - 设置器



- (void)setActionBtnTitle:(NSString *)actionBtnTitle
{
    _actionBtnTitle = actionBtnTitle;
    [self.centerButton setTitle:actionBtnTitle forState:UIControlStateNormal];
}

- (void)setActionBtnTitleColor:(UIColor *)actionBtnTitleColor
{
    _actionBtnTitleColor = actionBtnTitleColor;
    [self.centerButton setTitleColor:actionBtnTitleColor forState:UIControlStateNormal];
}

- (void)setActionBtnFont:(UIFont *)actionBtnFont
{
    _actionBtnFont = actionBtnFont;
    self.centerButton.titleLabel.font = actionBtnFont;
}

- (void)setActionBtnBackgroundColor:(UIColor *)actionBtnBackgroundColor
{
    _actionBtnBackgroundColor = actionBtnBackgroundColor;
    self.centerButton.backgroundColor = actionBtnBackgroundColor;
}
- (void)setActionBtnBorderColor:(UIColor *)actionBtnBorderColor
{
    _actionBtnBorderColor = actionBtnBorderColor;
    self.centerButton.layer.borderColor = actionBtnBorderColor.CGColor;
}
- (void)setActionBtnCornerRadius:(CGFloat)actionBtnCornerRadius
{
    _actionBtnCornerRadius = actionBtnCornerRadius;
    self.centerButton.layer.cornerRadius = actionBtnCornerRadius;
}

- (void)setContentOffest:(CGSize)contentOffest
{
    _contentOffest = contentOffest;
}


- (void)setShowEmptyViewCenterButton:(BOOL)showEmptyViewCenterButton{
    _showEmptyViewCenterButton = showEmptyViewCenterButton;
    self.showCenterButton = showEmptyViewCenterButton;
}

- (void)setShowCenterButton:(BOOL)showCenterButton{
    _showCenterButton = showCenterButton;
    self.centerButton.hidden = !showCenterButton;
}

#pragma mark - 获取
- (EmptyTextLabelAppearance *)textAppearance{
    return [CAIEmptyViewGlobalConfig sharedInstance].textAppearance;
}


#pragma mark - add添加

- (void)zx_addChildViewControllerInController:(UIViewController *)viewController
{
    if ([viewController.childViewControllers containsObject:self])
    {
        return;
    }
    [viewController addChildViewController:self];
    [viewController.view addSubview:self.view];
    self.view.alpha = 0;

    __weak __typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.view.alpha = 1;
    } completion:^(BOOL finished) {

        [weakSelf didMoveToParentViewController:viewController];
    }];
}


#pragma mark - 内部方法

// 获取最终的提示文本；
- (NSString *)zx_finallyTextLabelTitle:(NSString *)title withError:(NSError *)error
{
    if (title.length>0 && error && self.showErrorCodeOnLabelText)
    {
        NSString *titleWithErrorCode = [NSString stringWithFormat:@"%@(%@)",title,@(error.code)];
        return titleWithErrorCode;
    }
    return title;
}


#pragma mark - toast

- (void)zx_makeToastInViewController:(UIViewController *)viewController withError:(NSError *)error
{
    if ([viewController isKindOfClass:[UITableViewController class]] ||[viewController isKindOfClass:[UICollectionViewController class]])
     {
         ///预防崩溃
         if (error.domain) {
             [self showToast:[error localizedDescription] inView:viewController.view.window];
         }
     }
     else
     {
         if (error.domain) {
             [self showToast:[error localizedDescription] inView:viewController.view];
         }
     }
}


#pragma mark -hide
// 函数二：
- (void)removeEmptyViewInContainerViewConroller
{
    if (self.parentViewController)
    {
        [self willMoveToParentViewController:nil];
        
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }
}


#pragma mark - button selector

- (void)updateNewData:(UIButton *)sender
{
    if (self.buttonActionType == ZXEmptyViewActionTypeErrorSolution)
    {
        if ([CAIEmptyViewGlobalConfig sharedInstance].lookErrorSolutionActionBlock) {
            [CAIEmptyViewGlobalConfig sharedInstance].lookErrorSolutionActionBlock();
        }else{
            CAIErrorSolutionWebController *vc = [[CAIErrorSolutionWebController alloc] init];
            vc.localHtmlFilePath = [CAIEmptyViewGlobalConfig sharedInstance].networkErrorHelpHtmlPath;
            if (self.parentViewController.navigationController) {
                vc.hidesBottomBarWhenPushed = YES;
                [self.parentViewController.navigationController pushViewController:vc animated:NO];
            }
        }
    }
    else if (self.buttonActionType == ZXEmptyViewActionTypeReload)
    {
         [self checkNetworkReachableWithButtonActionType:self.buttonActionType];
    }
    else
    {
        [self btnAndEventActionWithButtonActionType:self.buttonActionType];
    }
}


#pragma mark - touchBegan

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    // MBBackgroundView,UIView
    UIView *view = [[[touches allObjects] firstObject] view];
    if ([view isEqual:self.view]) {
        if (self.touchEventType == ZXEmptyViewTouchEventTypeReload) {
            
            if ([self canPerformAction:@selector(checkNetworkReachableWithButtonActionType:) withSender:self]) {
                [self checkNetworkReachableWithButtonActionType:ZXEmptyViewActionTypeTouch];
            }
        }
    }
}

- (void)checkNetworkReachableWithButtonActionType:(ZXEmptyViewActionType)type
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
           switch (status) {

               case AFNetworkReachabilityStatusNotReachable:{
                   [self showToast:@"网络未连接,请检查后重试" inView:self.view];
                   break;
               }
               case AFNetworkReachabilityStatusReachableViaWiFi:
               case AFNetworkReachabilityStatusReachableViaWWAN:{
                   [self removeEmptyViewInContainerViewConroller];
                   [self btnAndEventActionWithButtonActionType:type];
                   break;
               }
               default:break;
           }
       }];
}



- (void)showToast:(NSString *)text inView:(UIView *)view{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.contentColor = [UIColor whiteColor];
    hud.label.text = text;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0 alpha:0.75f];
    [hud hideAnimated:YES afterDelay:1.5];
}


#pragma mark - action


- (void)btnAndEventActionWithButtonActionType:(ZXEmptyViewActionType)type
{
    if ([self.delegate respondsToSelector:@selector(emptyViewController:touchAndActionWithButtonActionType:)]) {
        [self.delegate emptyViewController:self touchAndActionWithButtonActionType:type];
        return;
    }

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
    if ([self.delegate respondsToSelector:@selector(zxEmptyViewTouchAndActionWithController:)]) {
        [self.delegate zxEmptyViewTouchAndActionWithController:self];
        return;
    }
#pragma clang diagnostic pop
}

#pragma mark -

+ (void)zx_makeToastInViewController:(UIViewController *)viewController withError:(NSError *)error
{
    [[self alloc]zx_makeToastInViewController:viewController withError:error];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (CGFloat)safeAreaStatusBarHeight
{
    return [EmptyViewKitTool safeAreaStatusBarHeight];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
